<template>
  <div class="star" :class="starType">
    <span v-for="itemClass in itemClasses" :class="itemClass" :key="itemClass.id" class="star-item"></span>
  </div>
</template>

<script type="text/ecmascript-6">
  const LENGTH = 5
  const CLS_ON = 'on'
  const CLS_HALF = 'half'
  const CLS_OFF = 'off'

  export default {
    props: {
      size: {
        type: Number
      },
      score: {
        type: Number
      }
    },
    data() {
      return {}
    },
    computed: {
      starType() { // 根据大小计算选择星号大小的类样式
        return 'star-' + this.size
      },
      itemClasses() { // 根据分数选择星号的类型（满星、半星、暗星）
        let result = []
        let score = Math.floor(this.score * 2) / 2 // 获取分数 只有三个类型的数量 （0  n.5  n）
        let hasDecimal = score % 1 !== 0 // 判断是否有n.5数字类型
        let integer = Math.floor(score)

        // 添加全星的在前面
        for (let i = 0; i < integer; i++) {
          result.push(CLS_ON)
        }

        // 判断是否有半颗星的放在后面
        if (hasDecimal) {
          result.push(CLS_HALF)
        }

        // 补全5颗星
        while (result.length < LENGTH) {
          result.push(CLS_OFF)
        }
        return result
      }
    }
  }
</script>

<style lang="less" rel="stylesheet/less">
  @import "./../../common/less/mixins";

  .star {
    font-size: 0;
    .star-item {
      display: inline-block;
      background-repeat: no-repeat;
    }
    &.star-48 {
      .star-item {
        width: 20px;
        height: 20px;
        margin-right: 22px;
        background-size: 20px 20px;
        &:last-child {
          margin-right: 0;
        }
        &.on {
          .bg-images('./../images/star/star48_on')
        }
        &.half {
          .bg-images('./../images/star/star48_half')
        }
        &.off {
          .bg-images('./../images/star/star48_off')
        }
      }
    }
    &.star-36 {
      .star-item {
        width: 15px;
        height: 15px;
        margin-right: 6px;
        background-size: 15px 15px;
        &:last-child {
          margin-right: 0;
        }
        &.on {
          .bg-images('./../images/star/star36_on')
        }
        &.half {
          .bg-images('./../images/star/star36_half')
        }
        &.off {
          .bg-images('./../images/star/star36_off')
        }
      }
    }
    &.star-24 {
      .star-item {
        width: 10px;
        height: 10px;
        margin-right: 3px;
        background-size: 110px 10px;
        &:last-child {
          margin-right: 0;
        }
        &.on {
          .bg-images('./../images/star/star24_on')
        }
        &.half {
          .bg-images('./../images/star/star24_half')
        }
        &.off {
          .bg-images('./../images/star/star24_off')
        }
      }
    }
  }
</style>
